//
//  DailyTalkNewsVC.m
//  Cunli
//
//  Created by lilubin on 15/6/19.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "DailyTalkNewsVC.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "NewsModel_yy.h"
#import "NewsCell.h"
#import "UIImageView+WebCache.h"
#import "NewDetailController.h"
#import "MJRefresh.h"
#import "Config.h"
#import "MBProgressHUD.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define pageSize 6

static NSString *kNewsCellID = @"NewsCell";

@interface DailyTalkNewsVC ()
{
    NSMutableArray *_datasArray; //存放消息模型的数组
    UIPageControl *_pageControl; //头视图中的指示control
    UIScrollView *_scrollView;   //头视图中的scrollView
    NSUInteger _scrollToIndex;   //滚动到第几张图片
    NSTimer *_imgTimer;          //图片循环的定时器
}


@end

@implementation DailyTalkNewsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initGlobalParams];
    [self reloadDataToNew:YES];
//    [self createHeaderView];
    [self registerNewsCell];
    [self addRefreshAttribute];
    self.tableView.separatorColor = [UIColor colorWithHexString:TableViewSeperateColorValue];
}

- (void)initGlobalParams
{
    _datasArray = [NSMutableArray arrayWithCapacity:6];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//设置部分控件的属性
- (void)setSomeAttributes
{
    _scrollToIndex = 0;
    _imgTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoScrollAction) userInfo:nil repeats:YES];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    
    //    [self.tableView.legendHeader beginRefreshing];
}

/*
- (void)testRefresh
{
    NSLog(@"Refresh");
}
 */


//自动滚动触发的函数
- (void)autoScrollAction
{
    //    NSLog(@"scrollToIndex:%li", _scrollToIndex);
    //    [UIView animateWithDuration:1 animations:^{
    [_scrollView setContentOffset:CGPointMake(_scrollToIndex * kScreenWidth, 0) animated:YES];
    _pageControl.currentPage = _scrollToIndex;
    //    }];
    _scrollToIndex++;
    if (_scrollToIndex == 2) {
        _scrollToIndex = 0;
        return;
    }
}

/*
//创建头视图
- (void)createHeaderView
{
    CGFloat headerHeight = 160;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, headerHeight)];
    self.tableView.tableHeaderView = headerView;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:headerView.frame];
    _scrollView.tag = 100;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(kScreenWidth * 2, headerHeight);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    //服务器端的pic的url无效，在网上随便找的一个图片来填充
    NSString *testImgURLStr = @"https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a925e529d443ad4ba67b1580e43f6e9d/ca1349540923dd542658bfe4d409b3de9c824816.jpg";
    NSURL *testImgURL = [NSURL URLWithString:testImgURLStr];
    
    for (int i = 0; i < 2; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*kScreenWidth, 0, kScreenWidth, headerHeight)];
        imageView.backgroundColor = [UIColor orangeColor];
        [imageView setImageWithURL:testImgURL];
        [_scrollView addSubview:imageView];
    }
    
    [headerView addSubview:_scrollView];
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, headerHeight-30, kScreenWidth, 30)];
    _pageControl.numberOfPages = 2;
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [headerView addSubview:_pageControl];
    
    //    [self setSomeAttributes];
    
}
 */

//注册tableViewCell
- (void)registerNewsCell
{
    UINib *nib = [UINib nibWithNibName:@"NewsCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kNewsCellID];
}

//初始化该控制器
- (instancetype)initWithDailyTalkType:(DailyTalkType)type
{
    self = [super init];
    if (self) {
        _dailyNewsType = type;
    }
    return self;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    NSLog(@"numberOfRows: dataArray.count:%ld", _datasArray.count);
    return _datasArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:kNewsCellID forIndexPath:indexPath];
    cell.newsModel = _datasArray[indexPath.row];
    return cell;
}

//将cell的高度固定为120
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

//进入新闻的详情界面只需要传itemid的值即可
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewDetailController *newDetailVC = [[NewDetailController alloc] init];
    NewsModel_yy *newModel2 = _datasArray[indexPath.row];
    newDetailVC.itemID = newModel2.itemid;
    newDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:newDetailVC animated:YES];
}

//加载数据
/*刷新or加载更多函数
 *@new
 *yes:刷新
 *no:加载更多
 */
- (void)reloadDataToNew:(BOOL)new
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString *typeStr = [NSString stringWithFormat:@"%d", _dailyNewsType];
    
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:typeStr forKey:@"type"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"6" forKey:@"pagesize"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    //    NSLog(@"count: %lu, All params:%@", CheckParams.count, CheckParams);
    
    [MyDataService requestURL:@"daytalk_newslist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        if ([response isEqualToString:@"news_list"]||[response isEqualToString:@"daytalk_newslist"]) {
            NSDictionary *newslistDic = result[@"newslist"];
            NSArray *newsList = newslistDic[@"list"];
            NSInteger totalCount = [newslistDic[@"totalcount"] integerValue];
            
            /*
             *思路：判断是否是刷新
             *是：移除dataArray中的数据，重新加载第一页
             *否：加载下一页的数据，并且拼接到已存在的数据数组中
             */
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                }
            }
            if (totalCount == _datasArray.count) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"没有更多数据";
                [hud hide:YES afterDelay:1];
                [self.tableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
                    NewsModel_yy *newModel = [NewsModel_yy yy_modelWithJSON:dataDic];
                    [_datasArray addObject:newModel];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.legendHeader endRefreshing];
                    [weakSelf.tableView.legendFooter endRefreshing];
                    [weakSelf.tableView reloadData];
                });
            }
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = text;
            [hud hide:YES afterDelay:1];
        }
        
    } failureAction:^{
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新闻数据获取错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertView show];
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"数据获取错误";
        [hud hide:YES afterDelay:1];

        [self.tableView.legendHeader endRefreshing];
        [self.tableView.legendFooter endRefreshing];
        
    }];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.tag == 100) {
        CGFloat xOffset = scrollView.contentOffset.x;
        
        _pageControl.currentPage = xOffset / kScreenWidth;
    }
}

//视图消失时，取消定时器
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [_imgTimer invalidate];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self setSomeAttributes];
}



@end
